//! Redis配置文件解析器
//! 
//! 完全兼容官方Redis配置文件格式 (.conf)

use crate::cluster::ClusterConfig;
use crate::config::config_loader::ConfigLoader;
use anyhow::{Result, anyhow};
use std::collections::HashMap;
use std::fs;
use std::path::Path;
use std::time::Duration;

/// Redis配置文件解析器
/// 
/// 实现ConfigLoader trait，支持官方Redis .conf格式
pub struct RedisConfigParser;

impl ConfigLoader for RedisConfigParser {
    fn load_from_file(&self, path: &Path) -> Result<ClusterConfig> {
        let content = fs::read_to_string(path)?;
        self.load_from_string(&content)
    }
    
    fn load_from_string(&self, content: &str) -> Result<ClusterConfig> {
        let config_map = Self::parse_config_content(content)?;
        Self::build_cluster_config(config_map)
    }
    
    fn supported_extensions(&self) -> Vec<&'static str> {
        vec!["conf"]
    }
    
    fn loader_name(&self) -> &'static str {
        "Redis Configuration Parser"
    }
    
    fn validate_format(&self, content: &str) -> bool {
        // 检查是否包含Redis配置特征
        let lines: Vec<&str> = content.lines().collect();
        let non_comment_lines: Vec<&str> = lines.iter()
            .filter(|line| !line.trim().is_empty() && !line.trim().starts_with('#'))
            .copied()
            .collect();
        
        if non_comment_lines.is_empty() {
            return false;
        }
        
        // 检查是否有常见的Redis配置项
        let redis_keywords = ["port", "bind", "cluster-enabled", "timeout", "maxclients"];
        non_comment_lines.iter().any(|line| {
            redis_keywords.iter().any(|keyword| {
                line.to_lowercase().starts_with(keyword)
            })
        })
    }
}

impl RedisConfigParser {
    /// 从Redis标准配置文件(.conf)解析配置
    pub fn parse_redis_conf<P: AsRef<Path>>(path: P) -> Result<ClusterConfig> {
        let parser = RedisConfigParser;
        parser.load_from_file(path.as_ref())
    }
    
    /// 解析配置文件内容
    fn parse_config_content(content: &str) -> Result<HashMap<String, String>> {
        let mut config_map = HashMap::new();
        
        for line in content.lines() {
            let line = line.trim();
            
            // 跳过注释和空行
            if line.is_empty() || line.starts_with('#') {
                continue;
            }
            
            // 解析键值对
            if let Some((key, value)) = Self::parse_config_line(line) {
                config_map.insert(key, value);
            }
        }
        
        Ok(config_map)
    }
    
    /// 解析单行配置
    fn parse_config_line(line: &str) -> Option<(String, String)> {
        let parts: Vec<&str> = line.splitn(2, char::is_whitespace).collect();
        if parts.len() == 2 {
            Some((parts[0].to_lowercase(), parts[1].trim().to_string()))
        } else {
            None
        }
    }
    
    /// 构建集群配置对象
    fn build_cluster_config(config_map: HashMap<String, String>) -> Result<ClusterConfig> {
        // 必需配置
        let redis_port = config_map.get("port")
            .ok_or_else(|| anyhow!("缺少必需配置: port"))?
            .parse::<u16>()?;
        
        let bind_addr = config_map.get("bind")
            .unwrap_or(&"127.0.0.1".to_string())
            .clone();
        
        // 集群端口计算
        let cluster_port = if let Some(bus_port) = config_map.get("cluster-announce-bus-port") {
            bus_port.parse::<u16>()?
        } else {
            redis_port + 10000  // 官方Redis默认规则
        };
        
        // 检查集群模式
        let cluster_enabled = config_map.get("cluster-enabled")
            .map(|v| v == "yes")
            .unwrap_or(false);
        
        if !cluster_enabled {
            return Err(anyhow!("配置文件未启用集群模式 (cluster-enabled yes)"));
        }
        
        // 生成节点ID
        let node_id = format!("redis-node-{redis_port}");
        
        // 解析超时配置
        let cluster_node_timeout = config_map.get("cluster-node-timeout")
            .unwrap_or(&"5000".to_string())
            .parse::<u64>()
            .unwrap_or(5000);
        
        let fail_timeout = Duration::from_millis(cluster_node_timeout);
        
        // 构建配置对象
        let mut config = ClusterConfig::new()
            .with_node_id(node_id)
            .with_bind_addr(bind_addr)
            .with_redis_port(redis_port)
            .with_cluster_port(cluster_port);
        
        // 设置超时
        config.fail_timeout = fail_timeout;
        config.heartbeat_interval = Duration::from_millis(cluster_node_timeout / 5);
        config.election_timeout = Duration::from_millis(cluster_node_timeout / 2);
        
        // 解析其他配置
        if let Some(maxclients) = config_map.get("maxclients") {
            if let Ok(_max_clients) = maxclients.parse::<u32>() {
                // TODO: 设置最大客户端数
            }
        }
        
        // 解析副本配置
        if let Some(replica_factor) = config_map.get("cluster-replica-validity-factor") {
            if let Ok(_factor) = replica_factor.parse::<u32>() {
                // TODO: 设置副本有效性因子
            }
        }
        
        // 解析迁移障壁
        if let Some(migration_barrier) = config_map.get("cluster-migration-barrier") {
            if let Ok(_barrier) = migration_barrier.parse::<u32>() {
                // TODO: 设置迁移障壁
            }
        }
        
        Ok(config)
    }
}

